package com.example.secondhandspringboot.controller;


import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.secondhandspringboot.constant.MessageConstant;
import com.example.secondhandspringboot.constant.RedisConstant;
import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.domain.dto.RequiredGoodsDTO;
import com.example.secondhandspringboot.domain.entity.RequiredGoods;
import com.example.secondhandspringboot.domain.entity.User;
import com.example.secondhandspringboot.domain.vo.RequiredGoodsVO;
import com.example.secondhandspringboot.exception.RequiredGoodsException;
import com.example.secondhandspringboot.exception.UserException;
import com.example.secondhandspringboot.results.PageResult;
import com.example.secondhandspringboot.results.Result;
import com.example.secondhandspringboot.service.IRequiredGoodsService;
import com.example.secondhandspringboot.utils.IpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周在林
 * @since 2024-04-25
 */
@RestController
@RequestMapping("/requiredGoods")
@CrossOrigin
@Slf4j
@RequiredArgsConstructor
public class RequiredGoodsController {

    private final IRequiredGoodsService requiredGoodsService;
    private final StringRedisTemplate stringRedisTemplate;

    //每个用户每天最多给某个商品增加热力值次数
    private static final int todayMaxClickedNum = 10;

    /**
     * 更新热力值
     */
    @PatchMapping("/{id}")
    public Result updateHeatingValue(@PathVariable Long id){
        log.info("更新热力值,求购id: "+id);
        Long userId = BaseContext.getCurrentId();
        String key = RedisConstant.HEATING_VALUE + id + "," + userId;
        if (id == null){
            Result.error("传入id为空");
        }
        //今日点击数量，一天最多20
        String value = stringRedisTemplate.opsForValue().get(key);
        if (value == null){
            stringRedisTemplate.opsForValue().set(key,"1");
        }else {
            //自增后的次数
            stringRedisTemplate.opsForValue().increment(key, 1);
            int nowNums = Integer.parseInt(stringRedisTemplate.opsForValue().get(key));
            if (nowNums > todayMaxClickedNum){
                return Result.error("您一天只能给同一商品增加"+todayMaxClickedNum+"点热力值哦，请明天再来");
            }
        }
        RequiredGoods requiredGoods = requiredGoodsService.getById(id);
        if (requiredGoods != null){
            //更新
            requiredGoods.setHeatingValue(requiredGoods.getHeatingValue()+1);
            requiredGoodsService.updateById(requiredGoods);
            return Result.success();
        }
        return Result.error("更新热力值发生错误");
    }

    /**
     * 保存求购信息
     * @param requiredGoodsDTO
     * @return
     */
    @PutMapping
    public Result saveRequiredGoods(@Validated @RequestBody RequiredGoodsDTO requiredGoodsDTO, HttpServletRequest request){
        log.info("保存求购信息,内容: "+requiredGoodsDTO.toString());
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null){
            throw new UserException(MessageConstant.USER_NOT_LOGIN);
        }
        requiredGoodsDTO.setUserId(currentId);
        requiredGoodsDTO.setCreateTime(LocalDateTime.now());
        requiredGoodsDTO.setUpdateTime(LocalDateTime.now());
        requiredGoodsDTO.setIpTerritory(IpUtil.ipReverse(request.getRemoteAddr())==null?"未知":IpUtil.ipReverse(request.getRemoteAddr()));
        requiredGoodsService.save(requiredGoodsDTO);
        return Result.success();
    }

    /**
     * 获取求购信息
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/getRequiredGoods")
    public Result<PageResult<RequiredGoodsVO>> getRequiredGoods(@RequestParam int page, @RequestParam int pageSize){
        log.info("获取求购信息,page:"+page+",pageSize: "+pageSize);
        Long currentUserId = BaseContext.getCurrentId();
        PageResult<RequiredGoodsVO> requiredGoodsVOS = requiredGoodsService.getRequiredGoods(page,pageSize,currentUserId);
        return Result.success(requiredGoodsVOS);
    }

    /**
     * 获取我的发布求购
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/getMyPushRequiredGoods")
    public Result<PageResult<RequiredGoodsVO>> getMyPushRequiredGoods(@RequestParam int page,
                                                                      @RequestParam int pageSize){
        log.info("分页获取我发布的所有求购");
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null){
            throw new UserException(MessageConstant.USER_NOT_LOGIN);
        }
        User user = Db.getById(currentId, User.class);
        if (user == null){
            throw new UserException(MessageConstant.USER_NOT_EXIST);
        }
        PageResult<RequiredGoodsVO> pageResult = requiredGoodsService.getMyPushRequiredGoods(page,pageSize,currentId);
        return Result.success(pageResult);
    }

    /**
     * 获取热力值
     * @param id
     * @return
     */
    @GetMapping("/getHeatingValue/{id}")
    public Result<Long> getHeatingValue(@PathVariable Long id){
        log.info("获取热力值,求购id: "+id);
        if (id == null){
            Result.error("传入id为空");
        }
        RequiredGoods requiredGoods = requiredGoodsService.getById(id);
        return Result.success(requiredGoods.getHeatingValue());
    }


    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result deletedByIds(@PathVariable String ids){
        log.info("批量删除,ids: "+ids);
        Long currentId = BaseContext.getCurrentId();
        if (currentId == null){
            throw new UserException(MessageConstant.USER_NOT_LOGIN);
        }
        if (ids == null){
            throw new RequiredGoodsException(MessageConstant.GOODS_DELETED_ERR);
        }
        requiredGoodsService.removeBatchByIds(Arrays.asList(ids.split(",")));
        return Result.success();
    }
}
